package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.PermissionMapper;
import com.itheima.mapper.RoleMapper;
import com.itheima.pojo.Permission;

import com.itheima.mapper.RoleMapper;

import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        String queryString = queryPageBean.getQueryString();
        //mybatis提供的分页查询插件
        PageHelper.startPage(currentPage,pageSize);
        //调用dao根据参数查询
        Page<Role> page = roleMapper.findByName(queryString);

        return new PageResult(page.getTotal(),page.getResult());
    }

    public void add(Integer[] integers, Role role) {
        //添加角色列表
        roleMapper.add(role);
        //获得添加角色返回的id
        Integer roleId = role.getId();
        //调用方法
        RoleAndPermission(integers,roleId);
    }

    public void RoleAndPermission(Integer[] permissionIds,Integer roleId){
        if (permissionIds != null && permissionIds.length > 0){
            List<Map<String,Integer>> list = new ArrayList<>();
            for (Integer permissionId : permissionIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("roleId",roleId);
                map.put("permissionId",permissionId);
                list.add(map);
            }
            //调用Dao添加角色与权限中间表
            roleMapper.addRolePermission(list);
        }
    }

    public List<Permission> findAll() {
        return permissionMapper.findAll();
    }

    public List<Integer> findPermissionIdsByRoleId(Integer roleId) {
        return roleMapper.findPermissionIdsByRoleId(roleId);
    }

    public void delete(Integer roleId){
        //根据id删除角色权限中间表
        roleMapper.deleteRoelPermission(roleId);
        //根据角色id删除角色
        roleMapper.deleteById(roleId);
    }

    public void update(Integer[] permissionIds, Integer roleId) {
        //根据角色id删除关联
        roleMapper.deleteRoelPermission(roleId);
        //根据角色id添加最新关联
        RoleAndPermission(permissionIds, roleId);

    }


    /**
     * 1.拉取所有的角色信息
     *
     * @return
     */
    @Override
    public List<Role> getRoleList() {
        return roleMapper.getRoleList();

    }
}
